package com.starblink.preferenceconfig.brandchoice.ui

import android.content.res.ColorStateList
import android.os.Build
import android.os.Bundle
import android.view.ViewGroup
import androidx.core.view.postDelayed
import androidx.viewbinding.ViewBinding
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.android.material.appbar.AppBarLayout
import com.starblink.android.basic.animators.FadeInAnimator
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.brv.annotaion.DividerOrientation
import com.starblink.android.basic.brv.utils.bindingAdapter
import com.starblink.android.basic.brv.utils.divider
import com.starblink.android.basic.brv.utils.grid
import com.starblink.android.basic.brv.utils.setup
import com.starblink.android.basic.config.ColdLaunchConfig
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.color
import com.starblink.android.basic.ext.dp
import com.starblink.android.basic.ext.toBean
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.util.ImageUtils
import com.starblink.android.basic.widget.LoadingDialogManager
import com.starblink.basic.log.SKLogger
import com.starblink.basic.route.RoutePage
import com.starblink.basic.storage.SkStorage
import com.starblink.preferenceconfig.R
import com.starblink.preferenceconfig.bean.Footer
import com.starblink.preferenceconfig.bean.PreferenceBrand
import com.starblink.preferenceconfig.databinding.ActivityBrandChoice1Binding
import com.starblink.preferenceconfig.databinding.ItemBrand1Binding
import com.starblink.preferenceconfig.databinding.ItemFooterBinding
import eightbitlab.com.blurview.BlurAlgorithm
import eightbitlab.com.blurview.RenderEffectBlur
import eightbitlab.com.blurview.RenderScriptBlur
import kotlin.math.absoluteValue

/**
 * 品牌选择
 */
@Route(path = RoutePage.PreferenceConfig.BRAND_CHOICE)
class BrandChoiceActivity : BaseTVMActivity<ActivityBrandChoice1Binding, BrandChoiceVM>() {
    override fun initViewBinding(): ActivityBrandChoice1Binding =
        ActivityBrandChoice1Binding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        pageExposure(pageElementValue = SpmPageDef.BrandPage)
        // 显示过，即不再显示
        SkStorage.put(ColdLaunchConfig.PREFERENCE_CONFIG_CHOOSE_OR_NOT, true)
    }

    override fun initData() {
        super.initData()
        intent.getStringExtra(
            RoutePage.PreferenceConfig.ARGS_PFEFERENCE_BRANDS
        )?.toBean<List<PreferenceBrand>>()?.let { viewModel.totalPreferenceList.addAll(it) }
    }

    override fun initView() {
        super.initView()
        initTopView()
        initBlurView()
        initListView()

        var params = HashMap<String, String>()
        viewBinding.btnBottom.apply {
            trackData(
                page = SpmPageDef.BrandPage,
                element = SpmElementDef.PreferenceDoneButton,
                params = params,
                onlyHit = true
            )

            click {
                val preferences: List<PreferenceBrand> =
                    viewBinding.rv.bindingAdapter.getCheckedModels()
                val ids = preferences.map { it.id }
                    .toList()
                    .joinToString(separator = ",")
                params["ids"] = ids
                viewModel.reportPreferenceBrandConfig(preferences)
            }
        }
    }

    /**初始化标题栏，头部部分*/
    private fun initTopView() {
        viewBinding.btnSkip.trackData(
            page = SpmPageDef.BrandPage,
            element = SpmElementDef.PreferenceSkipButton,
            onlyHit = true
        )
        viewBinding.btnSkip.click {
            viewModel.reportPreferenceBrandConfig(emptyList())
        }

        viewBinding.blurViewTopBar.alpha = 0f
        viewBinding.appBarLayout.addOnOffsetChangedListener { appBarLayout: AppBarLayout, verticalOffset: Int ->
//            YYLogUtils.e(
//                "appbarHeightdp:" + CommUtils.px2dip(appBarLayout.height) + " getTotalScrollRangedp:" + CommUtils.px2dip(appBarLayout.totalScrollRange) + " offSetdp:" + CommUtils.px2dip(verticalOffset),
//                "dss"
//            )
            viewBinding.blurViewTopBar.alpha =
                when (verticalOffset.absoluteValue) {
                    in 0..8.dp -> 0f
                    in 8.dp..80.dp -> verticalOffset.absoluteValue.toFloat() / 80.dp
                    else -> 1f
                }

            viewBinding.tvTitle.visibleOrGone(verticalOffset.absoluteValue >= 80.dp)
        }
    }

    private fun initBlurView() {
        //初始化毛玻璃效果
        viewBinding.blurViewTopBar.setupWith(viewBinding.root as ViewGroup, getBlurAlgorithm())
            .setBlurRadius(18f)
            .setBlurEnabled(true)

        viewBinding.blurViewBottomBar.setupWith(viewBinding.root as ViewGroup, getBlurAlgorithm())
            .setBlurRadius(18f)
            .setBlurEnabled(true)
    }

    private fun getBlurAlgorithm(): BlurAlgorithm {
        val algorithm: BlurAlgorithm
        algorithm = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            RenderEffectBlur()
        } else {
            RenderScriptBlur(mContext)
        }
        return algorithm
    }
    // 列表项点击时间，防止过快点击
    private var itemClickTime = 0L

    //初始化列表相关
    private fun initListView() {
        val animator = FadeInAnimator()
        animator.addDuration = 10
        viewBinding.rv.itemAnimator = animator
        viewBinding.rv.grid(3).divider {
            setDivider(12, true)
            orientation = DividerOrientation.GRID
        }.setup {
            addType<PreferenceBrand, ItemBrand1Binding>(it)
            addType<Footer, ItemFooterBinding>(it)

            onBind {
                when (val viewBinding = getBinding<ViewBinding>()) {
                    is ItemBrand1Binding -> {
                        val item =
                            getModel<PreferenceBrand>()

                        viewBinding.tvName.text = item.name
                        ImageUtils.loadImage(
                            context,
                            item.image ?: "",
                            viewBinding.ivIcon
                        )
                        // 选中项显示遮罩对勾
//                        viewBinding.vMask.visibleOrGone(item.isChecked)
                        viewBinding.vMask.visibleOrGone(item.isChecked)
                    }
                }
            }

            // 点击列表项，触发选中/取消选中
            onClick(R.id.root) {
                // 防止过快点击
                if(System.currentTimeMillis() - itemClickTime < 300) {
                    return@onClick
                }else{
                    itemClickTime = System.currentTimeMillis()
                }
                val model = getModel<PreferenceBrand>()
                if (model.isChecked) {
                    // 如果已选中，取消选中
                    setChecked(layoutPosition, false)
                } else {
                    // 如果未选中,选中之，并且尝试加载关联品牌
                    if (!model.isGotSimilarBrand) {
                        model.isGotSimilarBrand = true
                        viewModel.getSimilarPreferenceBrandList(
                            getModel<PreferenceBrand>().id
                        )
                    }
                    setChecked(layoutPosition, true)
                }
            }

            // 监听列表选中
            onChecked { position, isChecked, isAllChecked ->
                val model = getModel<PreferenceBrand>(position)
                model.isChecked = isChecked
                notifyItemChanged(position)

                // 更新按钮状态
                if (checkedCount >= 3) {
                    viewBinding.btnBottom.text = "Done ($checkedCount)"
                    setBottomBtnEnable(true)
                } else {
                    viewBinding.btnBottom.text =
                        getString(com.starblink.basic.style.R.string.select_at_least_3)
                    setBottomBtnEnable(false)
                }
            }
        }
        viewBinding.rv.bindingAdapter.apply {
            toggle(true) //支持多选
            models =viewModel.totalPreferenceList
            addFooter(Footer())
        }
    }sealed class

    private fun setBottomBtnEnable(enable: Boolean){
        viewBinding.btnBottom.isEnabled = enable
        viewBinding.btnBottom.backgroundTintList = ColorStateList.valueOf(viewBinding.btnBottom.color( if(enable) com.starblink.basic.style.R.color.gu_text_data_brand else com.starblink.basic.style.R.color.gu_bg_brand4))
    }

    override fun initObservable() {
        super.initObservable()
        viewModel.similarBrandListLD.observe(this) {
            val brandId = it.first
            val relevantBrandList = it.second

            // 找到指定品牌ID所在位置
            var position: Int = -1
            viewModel.totalPreferenceList.forEachIndexed { index, preferenceBrand ->
                if(preferenceBrand.id == brandId){
                    position = index
                    return@forEachIndexed
                }
            }
            if(position == -1){
                return@observe // 找不到，结束执行
            }
            viewModel.totalPreferenceList.addAll(position + 1, relevantBrandList)

            // 更新viewBinding.rv.bindingAdapter.checkedPosition
            val checkedPositions = mutableListOf<Int>()
            viewModel.totalPreferenceList.forEachIndexed { index, preferenceBrand ->
                if(preferenceBrand.isChecked){
                    checkedPositions.add(index)
                }
            }

            viewBinding.rv.bindingAdapter.checkedPosition.clear()
            viewBinding.rv.bindingAdapter.checkedPosition.addAll(checkedPositions)

            viewBinding.rv.bindingAdapter.notifyDataSetChanged()
        }

        viewModel.goToChooseCompletePageLD.observe(this) {
            goToChooseCompletePage(it)
        }
    }

    private fun goToChooseCompletePage(preferenceBrands: List<PreferenceBrand>) {
        navigationTo(RoutePage.PreferenceConfig.CHOOSE_COMPLETE) {
            withObject(
                RoutePage.PreferenceConfig.ARGS_SELECTED_BRANDS,
                preferenceBrands
            )
        }
        viewBinding.root.postDelayed(100){
            finish()
        }
    }

    private fun goToMainPage() {
        // 去除无用参数
        getIntent().extras?.remove(RoutePage.PreferenceConfig.ARGS_PFEFERENCE_BRANDS)

        navigationTo(RoutePage.Main.MAIN_ACTIVITY) {
            with(getIntent().extras) // !!!将启动页的Bundle值（如果有）带入首页
        }
        viewBinding.root.postDelayed(100){
            finish()
        }
    }
}